<template>
  <form-dialog ref="formDrawerRef" :title="title" width="95%" top="2vh" :destroyOnClose="true" :isButton="!isView"
    @submit="handleSubmitMaintain">
    <div class="dialog-body" style="height: auto;">
      <el-divider content-position="left">客户信息</el-divider>
      <el-form ref="formRef" :model="form" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="6" v-for="item in configList" :key="item.value">
            <el-form-item :label="item.label" :prop="item.value">
              <template v-if="item.types === 'input'">
                <el-input v-model="form[item.value]" :placeholder="item.placeholder" :disabled="item.disabled"
                  maxlength="30" />
              </template>
              <template v-else-if="item.types === 'selectInput'">
                <el-autocomplete v-model="form[item.value]" :fetch-suggestions="handleQuerySearchAsync"
                  :trigger-on-focus="false" value-key="licensePlate" placeholder="请输入车牌号" clearable
                  @select="handleSelectLicensePlate" :disabled="item.disabled" style="width: 100%">
                </el-autocomplete>
              </template>
              <template v-else-if="item.types === 'inputNumber'">
                <el-input v-model="form[item.value]" type="number" :min="1" :disabled="item.disabled"
                  :placeholder="item.placeholder"><template #append>{{ item.unit }}</template></el-input>
              </template>
              <template v-else-if="item.types === 'select'">
                <el-select v-model="form[item.value]" :placeholder="item.placeholder" :disabled="item.disabled"
                  filterable>
                  <el-option v-for="option in item.options" :key="option.value" :label="option.label"
                    :value="option.value"></el-option>
                </el-select>
              </template>
              <template v-else-if="item.types === 'date'">
                <el-date-picker v-model="form[item.value]" :placeholder="item.placeholder" :disabled="item.disabled"
                  type="date" value-format="YYYY-MM-DD HH:mm:ss" :disabled-date="handleDisabledDate"
                  style="width: 100%"></el-date-picker>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider content-position="left">现场作业照片(前后左右)</el-divider>
      <div class="flex">
        <upload-img class="mr-2" v-for="item in configImg" :key="item" :disabled="isView" :imgList="form[item]"
          @success="handleUpdateImg($event, item)"></upload-img>
      </div>
      <el-divider content-position="left">服务项目</el-divider>
      <div v-if="!isView" class="flex justify-end mb-2">
        <el-button type="primary" @click="handleCreateProject()">添加项目</el-button>
      </div>
      <div class="dialog-project">
        <template v-if="form.projectList.length">
          <el-card class="mb-2" v-for="(item, index) in form.projectList" :key="item.projectName">
            <template #header>
              <div class="flex justify-between items-center">
                <div>
                  <span class="font-bold text-base">{{ item.projectName }}</span>
                  <span class="ml-4">项目工时:<span>{{ item.duration }}</span>
                  </span>
                </div>
                <div v-if="!isView">
                  <el-button type="primary" @click="handleAddAccessory(index)">添加配件</el-button>
                  <el-popconfirm title="确定删除该服务项目？" width="200" @confirm="handleDeleteProject(index)">
                    <template #reference><el-button type="danger">删除项目</el-button></template>
                  </el-popconfirm>
                </div>
              </div>
            </template>
            <el-table :data="item.productList">
              <el-table-column label="配件名称" prop="productName"> </el-table-column>
              <el-table-column prop="productCode" label="配件编号" />
              <el-table-column prop="num" label="配件数量" />
              <el-table-column label="操作" v-if="!isView">
                <template #default="{ row, $index }">
                  <el-button type="primary" @click="handleEidtAccessoryBtn(row, index, $index)">编辑</el-button>
                  <el-popconfirm title="确定删除该配件？" width="200" @confirm="handleDeleteAccessory(index, $index)">
                    <template #reference><el-button type="danger">删除</el-button></template>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </template>
        <el-empty v-else description="暂无项目" />
      </div>
    </div>
    <!-- 添加打印按钮 -->
    <div class="flex justify-center mb-2" v-if="isView">
      <el-button type="primary" class="print-button" @click="handlePrint">打印</el-button>
      <el-button type="primary" class="print-button" @click="electronicSignatureFun">电子签章</el-button>
    </div>
    <!-- 添加项目 -->
    <form-drawer ref="formDrawerProjectRef" title="添加项目" :appendToBody="true" @submit="handleSumbitAddProject">
      <el-form ref="formProjectRef" :model="formProject" :rules="rulesProject" label-width="120">
        <el-form-item label="维修项目" prop="projectName">
          <el-input v-model="formProject.projectName" placeholder="请输入维修项目" />
        </el-form-item>
        <el-form-item label="维修工时" prop="duration">
          <el-input v-model="formProject.duration" v-integer-number placeholder="请输入维修工时" type="number" :min="1" />
        </el-form-item>
      </el-form>
    </form-drawer>
    <!-- 添加配件 -->
    <form-drawer ref="formDrawerAccessoryRef" title="添加配件" :appendToBody="true" @submit="handleSubmitAddAccessory">
      <el-form ref="formAccessoryRef" :model="formAccessory" :rules="rulesAccessory" label-width="120">
        <el-form-item label="配件名称" prop="productName">
          <el-input v-model="formAccessory.productName" placeholder="请输入配件名称" />
        </el-form-item>
        <el-form-item label="配件编码" prop="productCode">
          <el-input v-model="formAccessory.productCode" placeholder="请输入配件编码" />
        </el-form-item>
        <el-form-item label="配件数量" prop="num">
          <el-input v-model="formAccessory.num" v-integer-number placeholder="请输入配件数量" type="number" :min="1" />
        </el-form-item>
      </el-form>
    </form-drawer>
  </form-dialog>
  <el-dialog v-model="electronicSignatureDialog" title="盖章（将印章拖放至需要位置）" fullscreen>
    <electronic-signature :data="form"></electronic-signature>
  </el-dialog>
</template>
<script setup lang="ts">
import { onMounted, ref, toRefs, watch, computed } from "vue";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import FormDialog from "@/components/FormDialog.vue";
import FormDrawer from "@/components/FormDrawer.vue";
import { energyTypeList, colorTypeList } from "@/enum/index";
import { useInitForm } from "@/hooks/useCommon";
import { isCarNum, isIntegerNumber } from "@/utils/regular";
import {
  getEnterpriseListApi,
  getQualityCheckerListApi,
  addSecondMaintainRecordApi,
  getEnterpriseCardInfoByLicensePlateApi
} from "@/api/second";

import electronicSignature from './electronicSignature.vue';

const emits = defineEmits(["success"]);
const props = defineProps({
  isView: {
    type: Boolean,
    default: false
  },
  type: {
    type: Number,
    default: 1
  }
});
const { isView, type } = toRefs(props);
const title = computed(() => {
  switch (type.value) {
    case 1:
      return "新增";
    case 2:
      return "编辑";
    default:
      return "查看";
  }
});
const configList = ref([
  {
    types: "selectInput",
    label: "车牌号",
    value: "licensePlate",
    placeholder: "请输入车牌号",
    disabled: false
  }, {
    types: "select",
    label: "车牌颜色",
    value: "licensePlateColor",
    placeholder: "请选择车牌颜色",
    disabled: false,
    options: colorTypeList
  }, {
    types: "input",
    label: "车架号(VIN)",
    value: "bodyNo",
    placeholder: "请输入车架号(VIN)",
    disabled: false
  }, {
    types: "input",
    label: "发动机型号",
    value: "engineNo",
    placeholder: "请输入发动机型号",
    disabled: false
  }, {
    types: "input",
    label: "车辆品牌",
    value: "carBrand",
    placeholder: "请输入车辆品牌",
    disabled: false
  }, {
    types: "inputNumber",
    label: "出厂里程标识值",
    value: "mileageNum",
    placeholder: "请输入出厂里程标识值",
    disabled: false,
    unit: "KM"
  }, {
    types: "date",
    label: "接车日期",
    value: "acceptDate",
    placeholder: "请选择接车日期",
    disabled: false
  }, {
    types: "date",
    label: "进厂日期",
    value: "repairDate",
    placeholder: "请选择进厂日期",
    disabled: false
  }, {
    types: "date",
    label: "结算日期",
    value: "settleDate",
    placeholder: "请选择结算日期",
    disabled: false
  }, {
    types: "select",
    label: "燃料(能源)类型",
    value: "energyType",
    placeholder: "请选择燃料(能源)类型",
    disabled: false,
    options: energyTypeList
  }, {
    types: "input",
    label: "故障描述",
    value: "errorDesc",
    placeholder: "请输入故障描述",
    disabled: false
  }, {
    types: "inputNumber",
    label: "质量保证期(里程)",
    value: "qualityAssuranceMileage",
    placeholder: "请输入质量保证期(里程)",
    disabled: false,
    unit: "KM"
  }, {
    types: "inputNumber",
    label: "质量保证期(天数)",
    value: "qualityAssuranceDays",
    placeholder: "请输入质量保证期(天数)",
    disabled: false,
    unit: "天"
  }, {
    types: "select",
    label: "托修方",
    value: "companyId",
    placeholder: "请选择托修方",
    disabled: false,
    options: []
  }, {
    types: "select",
    label: "质量检验员",
    value: "qualityInspectorId",
    placeholder: "请选择质量检验员",
    disabled: false,
    options: []
  }
]);
const configImg = ref(["carImgFront1", "carImgBack1", "carImgLeft1", "carImgRight1"]);
// 维修
let { formDrawerRef, formRef, form, rules, handleCreate, handleEdit, handleSubmit } = useInitForm({
  form: {
    id: "",
    licensePlate: "",
    licensePlateColor: "",
    bodyNo: "",
    engineNo: "",
    carBrand: "",
    mileageNum: "",
    acceptDate: "",
    repairDate: "",
    settleDate: "",
    energyType: "",
    errorDesc: "二级维护",
    qualityAssuranceMileage: "",
    qualityAssuranceDays: "",
    companyId: "",
    qualityInspectorId: "",
    carImgFront1: [],
    carImgBack1: [],
    carImgLeft1: [],
    carImgRight1: [],
    carImgFront: '',
    carImgBack: '',
    carImgLeft: '',
    carImgRight: '',
    projectList: []
  },
  rules: {
    licensePlate: [
      { required: true, message: "请输入车牌号", trigger: "blur" },
      {
        validator(rule: any, value: any, callback: any) {
          if (!isCarNum(value)) {
            callback(new Error("请输入正确的车牌号"));
          } else {
            callback();
          }
        }
      }
    ],
    licensePlateColor: [{ required: true, message: "请选择车牌颜色", trigger: "change" }],
    bodyNo: [
      { required: true, message: "请输入车架号", trigger: "blur" },
      {
        validator(rule: any, value: any, callback: any) {
          if (!/^[A-Za-z0-9]{17}$/.test(value)) {
            callback(new Error("请输入正确的车架号"));
          } else {
            callback();
          }
        }
      }
    ],
    engineNo: [{ required: true, message: "请输入发动机号", trigger: "blur" }],
    carBrand: [{ required: true, message: "请输入车牌品牌", trigger: "blur" }],
    mileageNum: [
      { required: true, message: "请输入送修里程", trigger: "blur" },
      {
        validator(rule: any, value: any, callback: any) {
          if (!isIntegerNumber(value)) {
            callback(new Error("请输入正整数"));
          } else {
            callback();
          }
        }
      }
    ],
    acceptDate: [
      {
        required: true,
        message: "请选择接车日期",
        trigger: "change"
      }
    ],
    repairDate: [{ required: true, message: "请选择进厂日期", trigger: "change" }],
    settleDate: [{ required: true, message: "请选择结算日期", trigger: "change" }],
    energyType: [{ required: true, message: "请选择能源类型", trigger: "change" }],
    errorDesc: [{ required: true, message: "请输入故障描述", trigger: "blur" }],
    qualityAssuranceMileage: [
      { required: true, message: "请输入质量保证里程", trigger: "blur" },
      {
        validator: (rule: any, value: any, callback: any) => {
          if (!isIntegerNumber(value)) {
            callback(new Error("请输入正整数"));
          } else {
            callback();
          }
        }
      }
    ],
    qualityAssuranceDays: [{ required: true, message: "请输入质量保证天数", trigger: "change" }],
    companyId: [{ required: true, message: "请选择托修方", trigger: "change" }],
    qualityInspectorId: [{ required: true, message: "请选择质检员", trigger: "change" }]
  },
  createData: addSecondMaintainRecordApi,
  updateData: addSecondMaintainRecordApi,
  success: () => {
    emits("success");
  }
});
// 车牌号搜索
const handleQuerySearchAsync = async (queryString: string, cb: any) => {
  console.log(queryString)
  const res = await getEnterpriseCardInfoByLicensePlateApi({ carPlate: queryString });
  cb(res);
};
// 选择车牌号
const handleSelectLicensePlate = (value: any) => {
  const { licensePlate, licensePlateColor, vin, engineType, vehicleModel, energyType, companyId } =
    value;
  form.licensePlate = licensePlate;
  form.licensePlateColor = licensePlateColor;
  form.bodyNo = vin;
  form.engineNo = engineType;
  form.carBrand = vehicleModel;
  form.energyType = energyType;
  form.companyId = companyId;
};
//上传图片
const handleUpdateImg = (e: any, name: string) => {
  form[name] = e;
};
// 项目-弹框
const {
  formDrawerRef: formDrawerProjectRef,
  formRef: formProjectRef,
  form: formProject,
  rules: rulesProject,
  handleCreate: handleCreateProject,
  handleSubmit: handleSumbitProject
} = useInitForm({
  form: {
    projectName: "",
    duration: ""
  },
  rules: {
    projectName: [{ required: true, message: "请输入维修项目", trigger: "blur" }],
    duration: [{ required: true, message: "请输入维修工时", trigger: "blur" }]
  },
  isRequest: true
});
// 配件-弹框
const {
  formDrawerRef: formDrawerAccessoryRef,
  formRef: formAccessoryRef,
  form: formAccessory,
  rules: rulesAccessory,
  handleCreate: handleCreateAccessory,
  handleEdit: handleEditAccessory,
  handleSubmit: handleSubmitAccessory
} = useInitForm({
  form: {
    productName: "",
    productCode: "",
    num: ""
  },
  rules: {
    productName: [{ required: true, message: "请输入配件名称", trigger: "blur" }],
    productCode: [{ required: true, message: "请输入配件编码", trigger: "blur" }],
    num: [{ required: true, message: "请输入配件数量", trigger: "blur" }]
  },
  isRequest: true
});
// 添加项目-确定
const handleSumbitAddProject = () => {
  form.projectList.push({
    projectName: formProject.projectName,
    duration: formProject.duration,
    productList: []
  });
  handleSumbitProject();
};
// 删除项目
const handleDeleteProject = (index: number) => {
  form.projectList.splice(index, 1);
};
// 是否编辑
const isEdit = ref(false);
// 当前要添加配件的项目index
const curProject = ref(0);
// 当前要添加配件的index
const curAccessory = ref(0);
// 添加配件-按钮
const handleAddAccessory = (index: number) => {
  curProject.value = index;
  isEdit.value = false;
  handleCreateAccessory();
};

// 添加配件-确定
const handleSubmitAddAccessory = () => {
  const curItem = form.projectList[curProject.value].productList;
  if (isEdit.value) {
    curItem[curAccessory.value] = {
      productName: formAccessory.productName,
      productCode: formAccessory.productCode,
      num: formAccessory.num
    };
  } else {
    curItem.push({
      productName: formAccessory.productName,
      productCode: formAccessory.productCode,
      num: formAccessory.num
    });
  }
  handleSubmitAccessory();
};
// 编辑配件
const handleEidtAccessoryBtn = (row: any, pindex: number, aindex: number) => {
  curAccessory.value = aindex;
  curProject.value = pindex;
  isEdit.value = true;
  handleEditAccessory(row);
};
// 删除配件
const handleDeleteAccessory = (pindex: number, aindex: number) => {
  form.projectList[pindex].productList.splice(aindex, 1);
};
// 当前日期后面的时间不可选
const handleDisabledDate = (time: any) => {
  return time.getTime() > Date.now();
};
// 添加打印方法
const handlePrint = () => {
  window.print();
}

//电子签章
let electronicSignatureDialog = ref(false)
const electronicSignatureFun = () => {
  electronicSignatureDialog.value = true
}

// 确定
const handleSubmitMaintain = () => {
  const curAcceptDate = dayjs(form.acceptDate).valueOf();
  const curRepairDate = dayjs(form.repairDate).valueOf();
  const curSettleDate = dayjs(form.settleDate).valueOf();
  if (curAcceptDate > curRepairDate) {
    return ElMessage({
      showClose: true,
      message: "接车日期不能大于进厂时间",
      type: "warning"
    });
  }
  if (curRepairDate > curSettleDate) {
    return ElMessage({
      showClose: true,
      message: "结算日期不能小于进厂日期",
      type: "warning"
    });
  }
  if (
    !form.carImgFront1.length ||
    !form.carImgBack1.length ||
    !form.carImgLeft1.length ||
    !form.carImgRight1.length
  ) {
    return ElMessage({
      showClose: true,
      message: "请上传现场作业车辆前后左右图片",
      type: "warning"
    });
  }
  if (form.projectList.length <= 0) {
    return ElMessage({
      showClose: true,
      message: "至少添加一个服务项目",
      type: "warning"
    });
  }

  form.carImgFront = form.carImgFront1[0].url;
  form.carImgBack = form.carImgBack1[0].url;
  form.carImgLeft = form.carImgLeft1[0].url;
  form.carImgRight = form.carImgRight1[0].url;
  handleSubmit();
};

// 获取客运企业列表
const handleGetEnterpriseList = async () => {
  try {
    const res = await getEnterpriseListApi({});
    if (res) {
      const options = (res as any).map((item: any) => {
        return {
          label: item.companyName,
          value: item.id
        };
      });
      configList.value = configList.value.map((item) => {
        if (item.value === "companyId") {
          item.options = options;
        }
        return item;
      });
    }
  } catch (error) {
    console.log(error);
  }
};

// 获取质量检验员列表
const handleGetQualityCheckerList = async () => {
  try {
    const res = await getQualityCheckerListApi({
      position: "2"
    });
    if (res) {
      const options = (res as any).map((item: any) => {
        return {
          label: item.name,
          value: item.id
        };
      });
      configList.value = configList.value.map((item) => {
        if (item.value === "qualityInspectorId") {
          item.options = options;
        }
        return item;
      });
    }
  } catch (error) {
    console.log(error);
  }
};

onMounted(() => {
  handleGetEnterpriseList();
  handleGetQualityCheckerList();
});

watch(
  () => isView.value,
  (val) => {
    configList.value.forEach((item) => (item.disabled = val));
  },
  {
    immediate: true
  }
);

defineExpose({
  handleCreate,
  handleEdit,
  form
});
</script>
<style scoped lang="scss">
.dialog-body {
  height: calc(100vh - 180px);
  overflow-x: hidden;
  overflow-y: auto;
}

@media print {
  .print-button {
    display: none;
  }
}
</style>
